﻿#if UNITY_IOS
using System;
using System.Threading;
using Unity.Notifications.iOS;

namespace Notifications.Runtime.iOS
{
    public class iOSBackgroundNotificationTask : IDisposable
    {
        public const int TICK_TIME = 1000;
        public iOSBackgroundGameNotification Notification { get; set; }
        private Thread _monitorThread;
        public iOSBackgroundNotificationTask(iOSBackgroundGameNotification notification)
        {
            Notification = notification;
        }
        
        public void SendNotification()
        {
            Notification.SetNeedClose(false);
            KillThread();
            _monitorThread = new Thread(Update);
            _monitorThread.Start();
        }
        
        public void Wait()
        {
            KillThread();
        }
        
        public void ClearNotification()
        {
            KillThread();
            iOSNotificationCenter.RemoveDeliveredNotification(Notification.InternalNotification.Identifier);
        }

        private void Update()
        {
            while (GameNotificationsManager.IsInstanceCreated)
            {
                if (Notification.NeedClose())
                {
                    iOSNotificationCenter.RemoveDeliveredNotification(Notification.InternalNotification.Identifier);
                }
                else
                {
                    iOSNotificationCenter.ScheduleNotification(Notification.InternalNotification);
                }
                Thread.Sleep(TICK_TIME);
            }
        }

        private void KillThread()
        {
            if (_monitorThread!= null)
            {
                _monitorThread.Abort();
                _monitorThread.IsBackground = true;
            }
            _monitorThread = null;
        }

        public void Dispose()
        {
            KillThread();
        }
    }
}
#endif